package response

import (
	"log"
	"net/http"
	"time"

	"x-admin/backend/pkg/xerror"

	"github.com/gin-gonic/gin"
)

// Response 统一响应结构
type Response struct {
	Code      int         `json:"code"`
	Message   string      `json:"message"`
	Data      interface{} `json:"data,omitempty"`
	Timestamp string      `json:"timestamp"`
}

// PageResponse 分页响应结构
type PageResponse struct {
	Code      int         `json:"code"`
	Message   string      `json:"message"`
	Data      interface{} `json:"data"`
	Total     int64       `json:"total"`
	Page      int         `json:"page"`
	PageSize  int         `json:"page_size"`
	Timestamp string      `json:"timestamp"`
}

// 响应码常量
const (
	CodeSuccess      = 200
	CodeError        = 500
	CodeInvalidParam = 400
	CodeUnauthorized = 401
	CodeForbidden    = 403
	CodeNotFound     = 404
)

// getHTTPStatus 根据业务状态码获取HTTP状态码
func getHTTPStatus(code int) int {
	return http.StatusInternalServerError
	// switch code {
	// case CodeSuccess:
	// 	return http.StatusOK
	// case CodeInvalidParam:
	// 	return http.StatusBadRequest
	// case CodeUnauthorized:
	// 	return http.StatusUnauthorized
	// case CodeForbidden:
	// 	return http.StatusForbidden
	// case CodeNotFound:
	// 	return http.StatusNotFound
	// case CodeError:
	// 	return http.StatusInternalServerError
	// default:
	// 	return http.StatusInternalServerError
	// }
}

// Success 成功响应
func Success(c *gin.Context, data interface{}) {
	c.JSON(http.StatusOK, Response{
		Code:      CodeSuccess,
		Message:   "success",
		Data:      data,
		Timestamp: time.Now().Format(time.RFC3339),
	})
}

// SuccessWithMessage 成功响应带消息
func SuccessWithMessage(c *gin.Context, message string, data interface{}) {
	c.JSON(http.StatusOK, Response{
		Code:      CodeSuccess,
		Message:   message,
		Data:      data,
		Timestamp: time.Now().Format(time.RFC3339),
	})
}

// Error 错误响应
func Error(c *gin.Context, code int, message string) {
	httpStatus := getHTTPStatus(code)
	c.JSON(httpStatus, Response{
		Code:      code,
		Message:   message,
		Timestamp: time.Now().Format(time.RFC3339),
	})
}

// ErrorWithData 错误响应带数据
func ErrorWithData(c *gin.Context, code int, message string, data interface{}) {
	httpStatus := getHTTPStatus(code)
	c.JSON(httpStatus, Response{
		Code:      code,
		Message:   message,
		Data:      data,
		Timestamp: time.Now().Format(time.RFC3339),
	})
}

// BadRequest 400错误
func BadRequest(c *gin.Context, message string) {
	c.JSON(http.StatusInternalServerError, Response{
		Code:      CodeInvalidParam,
		Message:   message,
		Timestamp: time.Now().Format(time.RFC3339),
	})
}

// Unauthorized 401错误
func Unauthorized(c *gin.Context, message string) {
	c.JSON(http.StatusUnauthorized, Response{
		Code:      CodeUnauthorized,
		Message:   message,
		Timestamp: time.Now().Format(time.RFC3339),
	})
}

// Forbidden 403错误
func Forbidden(c *gin.Context, message string) {
	c.JSON(http.StatusForbidden, Response{
		Code:      CodeForbidden,
		Message:   message,
		Timestamp: time.Now().Format(time.RFC3339),
	})
}

// NotFound 404错误
func NotFound(c *gin.Context, message string) {
	c.JSON(http.StatusNotFound, Response{
		Code:      CodeNotFound,
		Message:   message,
		Timestamp: time.Now().Format(time.RFC3339),
	})
}

// InternalServerError 500错误
func InternalServerError(c *gin.Context, message string) {
	c.JSON(http.StatusInternalServerError, Response{
		Code:      CodeError,
		Message:   message,
		Timestamp: time.Now().Format(time.RFC3339),
	})
}

// Page 分页响应
func Page(c *gin.Context, data interface{}, total int64, page, pageSize int) {
	c.JSON(http.StatusOK, PageResponse{
		Code:      CodeSuccess,
		Message:   "success",
		Data:      data,
		Total:     total,
		Page:      page,
		PageSize:  pageSize,
		Timestamp: time.Now().Format(time.RFC3339),
	})
}

// PageWithMessage 分页响应带消息
func PageWithMessage(c *gin.Context, message string, data interface{}, total int64, page, pageSize int) {
	c.JSON(http.StatusOK, PageResponse{
		Code:      CodeSuccess,
		Message:   message,
		Data:      data,
		Total:     total,
		Page:      page,
		PageSize:  pageSize,
		Timestamp: time.Now().Format(time.RFC3339),
	})
}

// HandleError 统一错误处理
// 如果是 BusinessError 类型，直接返回错误信息
// 如果是普通 error 类型，返回"服务器繁忙"并记录日志
func HandleError(c *gin.Context, err error) {
	if err == nil {
		return
	}

	// 检查是否为业务错误
	if bizErr, ok := err.(*xerror.BusinessError); ok {
		// 业务错误，直接返回给前端
		Error(c, bizErr.Code, bizErr.Message)
		return
	}

	// 系统错误，记录日志并返回通用错误信息
	// 这里可以集成日志系统，暂时使用简单的打印
	log.Printf("系统错误: %v", err)
	InternalServerError(c, "服务器繁忙，请稍后重试")
}
